//
//  TotalDataModel.swift
//  DaRings
//
//  Created by 尹琼 on 2022/11/18.
//

import UIKit
import MYModule
import CRPSmartRing

open class TrainingDetailWorkoutsRecordModel: NSObject {
    
    public var distance: CGFloat?
    public var goalDistance: CGFloat?
    
    // 秒
    public var time: Int?
    public var goalTime: Int?
    
    public var caloriesData: TrainingDetailTotalDataSubModel = TrainingDetailTotalDataSubModel()
    public var paceData: TrainingDetailTotalDataSubModel = TrainingDetailTotalDataSubModel()
    public var stepsData: TrainingDetailTotalDataSubModel = TrainingDetailTotalDataSubModel()
    public var heartRateData: TrainingDetailTotalDataSubModel = TrainingDetailTotalDataSubModel()
    public var timeData: TrainingDetailTotalDataSubModel = TrainingDetailTotalDataSubModel()
    public var distanceData: TrainingDetailTotalDataSubModel = TrainingDetailTotalDataSubModel()
    
    public var type: TrainingType = .unknown
    
    public lazy var subDatas: [TrainingDetailTotalDataSubModel] = [TrainingDetailTotalDataSubModel]()
    
    public lazy var progress: CGFloat = 0.0
        
    public var trainingModel: TrainingModel? {
        didSet {
            self.returnSubDatas()
        }
    }
    
    
    
    public func returnTitleAttributeString() -> NSMutableAttributedString? {
        guard let trainingModel = self.trainingModel else {
            return nil
        }
        //有目标
        //目标为距离
        if trainingModel.goalType == 3 {
            return self.returnDistanceAttString(isGoal: true, isTitle: true)
        }
        //目标为时间
        if trainingModel.goalType == 2 {
            return self.returnTimeAttString(isGoal: true, isTitle: true)
        }
        //目标为卡路里
        if trainingModel.goalType == 1 {
            return self.returnKcalAttString(isGoal: true, isTitle: true)
        }
        //目标为配速
        if trainingModel.goalType == 0 {
            return self.returnPaceAttString(isGoal: true, isTitle: true)
        }
        //没有目标
        //有距离
        if self.type.contents.contains(.distance) {
            return self.returnDistanceAttString(isGoal: false, isTitle: true)
        }
        //有时间
        if self.type.contents.contains(.time) {
            return self.returnTimeAttString(isGoal: false, isTitle: true)
        }
        //卡路里
        if self.type.contents.contains(.calorie) {
            return self.returnKcalAttString(isGoal: false, isTitle: true)
        }
        //有配速
        if self.type.contents.contains(.pace) {
            return self.returnPaceAttString(isGoal: false, isTitle: true)
        }
        return nil
    }
    
    public func returnSubtitleAttributeString() -> NSMutableAttributedString? {
        guard let trainingModel = self.trainingModel else {
            return nil
        }
        //有目标
        //目标为距离
        if trainingModel.goalType == 3 {
            if self.type.contents.contains(.time) {
                return self.returnTimeAttString(isGoal: false, isTitle: false)
            }
            if self.type.contents.contains(.calorie) {
                return self.returnKcalAttString(isGoal: false, isTitle: false)
            }
            if self.type.contents.contains(.pace) {
                return self.returnPaceAttString(isGoal: false, isTitle: false)
            }
            return nil
        }
        //目标为时间
        if trainingModel.goalType == 2 {
            //TODO: 这个逻辑暂时不加，后续看需求
            if self.type.contents.contains(.distance) {
                return self.returnDistanceAttString(isGoal: false, isTitle: false)
            }
//            if self.type.contents.contains(.calorie) {
//                return self.returnKcalAttString(isGoal: false, isTitle: false)
//            }
//            if self.type.contents.contains(.pace) {
//                return self.returnPaceAttString(isGoal: false, isTitle: false)
//            }
            return nil
        }
        //目标为卡路里
        if trainingModel.goalType == 1 {
            //TODO: 这个逻辑暂时不加，后续看需求
//            if self.type.contents.contains(.distance) {
//                return self.returnDistanceAttString(isGoal: false, isTitle: false)
//            }
            
            if self.type.contents.contains(.time) {
                if self.type.contents.count <= 4 {
                    return nil
                } else {
                    return self.returnTimeAttString(isGoal: false, isTitle: false)
                }
                
            }
            if self.type.contents.contains(.pace) {
                return self.returnPaceAttString(isGoal: false, isTitle: false)
            }
            return nil
        }
        //目标为配速
        if trainingModel.goalType == 0 {
            //TODO: 这个逻辑暂时不加，后续看需求
//            if self.type.contents.contains(.distance) {
//                return self.returnDistanceAttString(isGoal: false, isTitle: false)
//            }
            if self.type.contents.contains(.time) {
                return self.returnTimeAttString(isGoal: false, isTitle: false)
            }
            if self.type.contents.contains(.calorie) {
                return self.returnKcalAttString(isGoal: false, isTitle: false)
            }
            return nil
        }
        //没有目标
        //有距离
        if self.type.contents.contains(.distance) {
            if self.type.contents.contains(.time) {
                return self.returnTimeAttString(isGoal: false, isTitle: false)
            }
            if self.type.contents.contains(.calorie) {
                return self.returnKcalAttString(isGoal: false, isTitle: false)
            }
            if self.type.contents.contains(.pace) {
                return self.returnPaceAttString(isGoal: false, isTitle: false)
            }
            return nil
        }
        return nil
    }
    
    private func returnDistanceAttString(isGoal: Bool, isTitle: Bool) -> NSMutableAttributedString? {
        guard let trainingModel = self.trainingModel else {
            return nil
        }
        var attriText = self.returnDistanceString(distance: Double(trainingModel.distance)).toAttributed
            .font(Fonts.boldSystemFont(ofSize: isTitle ? 40: 18))
            .foregroundColor(UIColor.assist_222222).rawValue
        
        if isGoal {
            let goalAttriText = "\("/")\(self.returnDistanceString(distance: Double(trainingModel.goal)))".toAttributed
                .font(Fonts.systemFont(ofSize: isTitle ? 20: 18))
                .foregroundColor(UIColor.assist_222222).rawValue
            attriText.append(goalAttriText)
        }
        
        let unit = Unit.sharedInstance.myType.baseDistance.name
        let unitAttriText = unit.toAttributed
            .font(Fonts.systemFont(ofSize: isTitle ? 20: 18))
            .foregroundColor(UIColor.assist_222222).rawValue
        attriText.append(unitAttriText)
        
        return attriText
    }
    
    private func returnTimeAttString(isGoal: Bool, isTitle: Bool) -> NSMutableAttributedString? {
        guard let trainingModel = self.trainingModel else {
            return nil
        }
        var attriText = timeString(trainingModel.vaildTime).toAttributed
            .font(Fonts.boldSystemFont(ofSize: isTitle ? 40: 18))
            .foregroundColor(UIColor.assist_222222).rawValue
        
        if isGoal {
            let goalAttriText = "\("/")\(timeString(trainingModel.goal))".toAttributed
                .font(Fonts.systemFont(ofSize: isTitle ? 20: 18))
                .foregroundColor(UIColor.assist_222222).rawValue
            attriText.append(goalAttriText)
        }
        
        return attriText
    }
    
    private func returnKcalAttString(isGoal: Bool, isTitle: Bool) -> NSMutableAttributedString? {
        guard let trainingModel = self.trainingModel else {
            return nil
        }
        var attriText = trainingModel.kcal.normalTitle.toAttributed
            .font(Fonts.boldSystemFont(ofSize: isTitle ? 40: 18))
            .foregroundColor(UIColor.assist_222222).rawValue
        
        if isGoal {
            let goalAttriText = "\("/")\(trainingModel.goal)".toAttributed
                .font(Fonts.systemFont(ofSize: isTitle ? 20: 18))
                .foregroundColor(UIColor.assist_222222).rawValue
            attriText.append(goalAttriText)
        }
        
        let unit = "unit_calorie".language
        let unitAttriText = unit.toAttributed
            .font(Fonts.systemFont(ofSize: isTitle ? 20: 18))
            .foregroundColor(UIColor.assist_222222).rawValue
        attriText.append(unitAttriText)
        
        return attriText
    }
    
    private func returnPaceAttString(isGoal: Bool, isTitle: Bool) -> NSMutableAttributedString? {
        guard let trainingModel = self.trainingModel else {
            return nil
        }
        let pace = self.returnPace()
        var attriText = self.returnPaceString(pace: pace).toAttributed
            .font(Fonts.boldSystemFont(ofSize: isTitle ? 40: 18))
            .foregroundColor(UIColor.assist_222222).rawValue
        
        if isGoal {
            let goalAttriText = "\("/")\(self.returnPaceString(pace: Double(trainingModel.goal)))".toAttributed
                .font(Fonts.systemFont(ofSize: isTitle ? 20: 18))
                .foregroundColor(UIColor.assist_222222).rawValue
            attriText.append(goalAttriText)
        }
        
        //TODO: 这个单位加上去好像很丑，暂时先不要
//        let unit = "gps_training_goal_setting_pace_current_unit".language
//        let unitAttriText = unit.toAttributed
//            .font(Fonts.systemFont(ofSize: isTitle ? 20: 18))
//            .foregroundColor(UIColor.assist_222222).rawValue
//        attriText.append(unitAttriText)
        
        return attriText
    }
    
    public func returnSubDatas(){
        guard let trainingModel = trainingModel else {
            return
        }
        var items = [TrainingTypeContent]()
        switch TrainingType.init(rawValue: trainingModel.type) {
        case .walking,
                .running,
                .gps_Run,
                .gps_TrailRun,
                .gps_Onfoot,
                .gps_Walking:
            items = TrainingTypeContent.allCases
            items.removeAll(.time)
            switch CRPSmartRing.CRPTrainingGoalType.init(rawValue: self.trainingModel?.goalType ?? 255) {
            case .some(.step):
                items.removeAll(.pace)
            case .some(.kcal):
                items.removeAll(.calorie)
            case .some(.exerciseTime):
                items.removeAll(.distance)
            case .some(.distance):
                items.removeAll(.distance)
            case .some(.none):
                items.removeAll(.distance)
                break
            default:
                items.removeAll(.distance)
                break
            }
        case .cycling,
                .skipping,
                .yoga,
                .fitness,
                .dancing,
                .elliptical,
                .indoorCycling,
                .rowing_machine,
                .freeTraining,
                .gps_Cycling:
            items = [.time, .calorie, .heartRate]
            switch CRPSmartRing.CRPTrainingGoalType.init(rawValue: self.trainingModel?.goalType ?? 255) {
            case .some(.kcal):
                items.removeAll(.calorie)
            case .some(.exerciseTime):
                items.removeAll(.time)
            case .some(.none):
                items.removeAll(.time)
                break
            default:
                items.removeAll(.time)
                break
            }
        case .badminton,
                .basketball,
                .football,
                .climbing,
                .tennis,
                .rugby,
                .golf,
                .baseball:
            items = [.time, .calorie, .step, .heartRate]
            switch CRPSmartRing.CRPTrainingGoalType.init(rawValue: self.trainingModel?.goalType ?? 255) {
            case .some(.kcal):
                items.removeAll(.calorie)
            case .some(.exerciseTime):
                items.removeAll(.time)
            case .some(.none):
                items.removeAll(.time)
                break
            default:
                items.removeAll(.time)
                break
            }
        default:
            break
        }
        
        self.caloriesData = TrainingDetailTotalDataSubModel(iconName: "ic_workout_popular_calories", value: "\(trainingModel.kcal.normalTitle)", unit: "gps_training_kcal".language, title: "training_rate_total_calories".language)
        
        let paceUnit = Unit.sharedInstance.myType.basePace.name
        self.paceData = TrainingDetailTotalDataSubModel(iconName: "ic_workout_popular_pace", value: self.returnPaceString(pace: self.returnPace()), unit: paceUnit, title: "training_pace".language)
        
        self.stepsData = TrainingDetailTotalDataSubModel(iconName: "ic_workout_popular_steps", value: "\(trainingModel.step.normalTitle)", unit: "", title: "gps_training_finish_total_steps".language)
        self.heartRateData = TrainingDetailTotalDataSubModel(iconName: "ic_workout_popular_hr", value: "\(trainingModel.heartRateAvg.normalTitle)", unit: "training_bpm_unit".language, title: "training_detail_item_avg_heart_rate_title".language)
        
        
        let distanceUnit = Unit.sharedInstance.myType.baseDistance.name
        self.distanceData = TrainingDetailTotalDataSubModel(iconName: "ic_workout_popular_hr", value: self.returnDistanceString(distance: Double(trainingModel.distance)), unit: distanceUnit, title: "training_detail_item_total_distance_title".language)
        self.timeData = TrainingDetailTotalDataSubModel(iconName: "ic_workout_popular_hr", value: timeString(time), unit: "", title: "training_detail_item_total_duration_title".language)
        
        if items.contains(.time) {
            self.subDatas.append(timeData)
        }
        if items.contains(.calorie) {
            self.subDatas.append(caloriesData)
        }
        if items.contains(.distance) {
            self.subDatas.append(distanceData)
        }
        if items.contains(.pace) {
            self.subDatas.append(paceData)
        }
        if items.contains(.step) {
            self.subDatas.append(stepsData)
        }
        if items.contains(.heartRate) {
            self.subDatas.append(heartRateData)
        }
        
    }
    
    open func timeString(_ second: Int?) -> String {
        guard let second = second else {
            return ""
        }
        
        let h: Int = second/3600
        let m: Int = (second - h * 3600)/60
        let s: Int = second - h * 3600 - m * 60
        
        return String(format: "%02d:%02d:%02d", h, m, s)
        
    }
    
    private func returnPace() -> Double {
        guard let trainingModel = self.trainingModel else {
            return 0.0
        }
        var pace = 0.0
        if trainingModel.distance > 0 {
            if Unit.sharedInstance.myType == .metric {
                pace = (Double(trainingModel.vaildTime) / 60.0) / (Double(trainingModel.distance) / 1000.0)
            } else {
                pace = (Double(trainingModel.vaildTime) / 60.0) / (Double(trainingModel.distance) * 100 / 16093 / 10.0)
            }
        }
        return pace
    }
    
    private func returnPaceString(pace: Double) -> String {
        let pace_tuple = Unit.sharedInstance.timeOf(seconds:  Int(pace * 1000.0 * 60.0)/1000, granularity: .minute)
        var paceStr = "\(pace_tuple.minute.leadingZero)'\(pace_tuple.second.leadingZero)\""
        if pace_tuple.minute == 0 && pace_tuple.second == 0 {
            paceStr = "--'--\""
        }
        return paceStr
    }
    
    private func returnDistanceString(distance: Double) -> String {
//        let number = Double(distance) / (Unit.sharedInstance.myType == .metric ? 1000.0 : 1609.3)
        
        let number = Unit.sharedInstance.goalDistance(distance).distance/1000.0
        
        let roundedNumber = ceil(number * 100) / 100
        let formattedNumber = String(format: "%.2f", roundedNumber)
        return distance > 0.0 ? "\(formattedNumber)" : "--"
    }
    
   
    
    
    
}
